package com.sun.service.user;

import com.sun.dao.BaseDao;
import com.sun.dao.user.UserDao;
import com.sun.dao.user.UserDaoImpl;
import com.sun.pojo.User;

import java.sql.Connection;
import java.util.List;

/**
 * @Author Sun
 * @Date 2020/4/25 11:22
 * @Version 1.0
 */
public class UserServiceImpl implements UserService {

    //用户业务层都会调用用户Dao层，所以需要引入UserDao层
    private UserDao userDao;
    public UserServiceImpl(){
        userDao = new UserDaoImpl();
    }

    public User login(String userCode, String password)  {
        Connection con = null;
        User user = null;

        try {
            con = BaseDao.getConnection();
            user = userDao.getLoginUser(con, userCode,password);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(con, null, null);
        }

        return user;
    }

    public boolean updatepwd(int id, String password) {
        Connection con = null;
        int affectRows = 0;
        boolean flag = false;

        try {
            con = BaseDao.getConnection();
            affectRows = userDao.updatepwd(con, id, password);//返回受影响的行数
            if(affectRows > 0){//如果受影响的行数大于0，代表修改成功
                flag=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(con, null, null);
        }
        return flag;
    }

    public int getUserCount(String userName, int userRole) {
        Connection connection = null;
        int count = 0;

        try {
            connection = BaseDao.getConnection();
            count = userDao.getUserCount(connection, userName, userRole);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(connection, null, null);
        }

        return count;
    }

    public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize) {
        Connection connection = null;
        List<User> userList = null;

        try {
            connection = BaseDao.getConnection();
            userList = userDao.getUserList(connection, userName, userRole, currentPageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(connection, null, null);
        }

        return userList;
    }

    public boolean addUser(User user) {
        Connection con = null;
        int affectRows = 0;
        boolean flag = false;

        try {
            con = BaseDao.getConnection();
            affectRows = userDao.addUser(con,user);
            if(affectRows > 0){//如果受影响的行数大于0，代表添加成功
                flag=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(con, null, null);
        }

        return flag;
    }


}
